package org.zfm.component;

import com.baomidou.mybatisplus.toolkit.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Service
public class EmailUtil {
    @Autowired
    private JavaMailSender javaMailSender;

    private final String addresser = "3214759100@qq.com";
    //邮箱校验
    public boolean isinValid(String email){
        //先判断 -- 格式是否正确
        if (!email.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")) {
            return false;
        }
        //@Todo 再判断是否是有效的邮箱

        return true;
    }

    /**
     * //简单邮件发送
     * @param recipients 收件人
     * @param title 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleEmail(String recipients,String title,String content){
        SimpleMailMessage message = new SimpleMailMessage();
        //设置发件人
        message.setFrom(addresser);
        //设置收件人
        message.setTo(recipients);
        //设置邮件主题
        message.setSubject(title);
        //设置邮件内容
        message.setText(content);
        //发送
        javaMailSender.send(message);
    }
    //复杂邮件发送

    /**
     *
     * @param recipients 收件人 不能为空
     * @param title 邮件主题
     * @param content 邮件内容
     * @param isHtml 邮件内容是否是HTML（是否要转换为页面）
     * @param attachment 附件（key:附件名字，value:附件地址--绝对地址）
     */
    public void sendComplexEmail(String recipients, String title,
                                 String content,boolean isHtml, Map<String,String> attachment)
            throws MessagingException {
        System.out.println(javaMailSender);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //获取发送复杂邮件工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf8");
        //设置发送人
        helper.setFrom(addresser);
        //如果标题不为空，则为邮件添加标题
        if(!StringUtils.isEmpty(title)){
            helper.setSubject(title);
        }
        //如果邮件内容不为空，则为邮件添加内容
        if(!StringUtils.isEmpty(content)){
            helper.setText(content,isHtml);
        }
        //如果附加不为空，则为邮件添加附件
        if(!MapUtils.isEmpty(attachment)){
            Set<Map.Entry<String, String>> entries = attachment.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            while(iterator.hasNext()){
                Map.Entry<String, String> next = iterator.next();
                helper.addAttachment(next.getKey(),new File(next.getValue()));
            }
        }
        //添加 邮件收件人
        helper.setTo(recipients);
        //发送邮件
        javaMailSender.send(mimeMessage);
    }

}
